package com.redfisky.ssoj.service;

import com.redfisky.ssoj.dao.RoleMapper;
import com.redfisky.ssoj.dao.UserNewMapper;
import com.redfisky.ssoj.entity.Role;
import com.redfisky.ssoj.entity.UserDetailsNew;
import com.redfisky.ssoj.entity.UserNew;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service(value = "userSecurityService")
public class UserSecurityServiceImpl implements UserSecurityService, UserDetailsService {

    @Resource
    private UserNewMapper userNewMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userNewMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(UserNew record) {
        return userNewMapper.insert(record);
    }

    @Override
    public UserNew selectByPrimaryKey(Integer id) {
        return userNewMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<UserNew> selectAll() {
        return userNewMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(UserNew record) {
        return userNewMapper.updateByPrimaryKey(record);
    }

    /*UserDetailsService 自定义数据库实现 参考博客：
     * https://my.oschina.net/u/241688/blog/1795786*/

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserNew userNew = userNewMapper.selectByEmail(s);
        if (userNew == null) {
            throw new UsernameNotFoundException(s);
        }
        Integer userNewId = userNew.getId();
        List<Role> roleList = roleMapper.selectByUserNewId(userNewId);
        ArrayList<GrantedAuthority> grantedAuthorityArrayList = new ArrayList<>();
        for (Role role : roleList) {
            grantedAuthorityArrayList.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        UserDetailsNew userDetailsNew = new UserDetailsNew(userNewId, userNew.getUsername(), userNew.getPassword(), userNew.getMobile(), userNew.getEmail(), userNew.getModifedDate(), grantedAuthorityArrayList);
        return userDetailsNew;
    }
}
